﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.Remoting;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ECP.Service.Utilities;
using ECP.Model;
using ECP.Utilities;
using Microsoft.Win32;
using ECP.Utilities.Controls;

namespace ECP.Client
{
    public partial class LoginFrm : FormBase
    {
        private int LoginCount;
        private int AllowLoginCount = 3;
        public DataTable DTStaff = new DataTable(BaseStaffTable.TableName);

        public LoginFrm()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (this.CheckInput())
            {
                this.LoginCount++;
                this.Login();
                this.CheckAllowLoginCount();
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void CheckAllowLoginCount()
        {
            if (this.LoginCount >= this.AllowLoginCount)
            {
                this.txtPassword.Clear();
                this.txtUsername.Enabled = false;
                this.txtPassword.Enabled = false;
                this.btnConfirm.Enabled = false;
            }
        }

        private bool CheckInput()
        {
            if (this.LoginCount == this.AllowLoginCount)
            {
                this.txtPassword.Clear();
                this.txtUsername.Enabled = false;
                this.txtPassword.Enabled = false;
                this.btnConfirm.Enabled = false;
                return false;
            }
            if (this.txtUsername.Text.Length == 0)
            {
                XtraMessageBox.Show(AppMessage.Format(AppMessage.MSG0007, new string[] { AppMessage.MSG9957 }), AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                this.txtUsername.Focus();
                return false;
            }
            if (!BaseSystemInfo.AllowNullPassword && (this.txtPassword.Text.Length == 0))
            {
                XtraMessageBox.Show(AppMessage.Format(AppMessage.MSG0007, new string[] { AppMessage.MSG9964 }), AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                this.txtPassword.Focus();
                return false;
            }
            this.btnConfirm.Focus();
            return true;
        }

        private void FormOnLoad()
        {
            this.Cursor = Cursors.WaitCursor;
            this.GetLoginTo();
            this.txtUsername.Focus();
            if (BaseSystemInfo.SavePassword)
            {
                try
                {
                    RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\JGsoft\" + BaseConfiguration.Instance.SoftName, false);
                    if (key != null)
                    {
                        this.txtUsername.Text = (string)key.GetValue("CurrentUsername");
                        this.SetLoginTo((string)key.GetValue("LoginTo"));
                    }
                }
                catch
                {
                }
            }
            if (this.txtUsername.Text.Length > 0)
            {
                base.ActiveControl = this.txtPassword;
                this.txtPassword.Focus();
            }
            this.SetHelp();
            this.SetControlState();
            this.Cursor = Cursors.Default;
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                this.FormOnLoad();
            }
            catch (Exception exception)
            {
                base.ProcessException(exception);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void GetLoginTo()
        {
            DataTable data = new DataTable();
            data.Columns.Add("ID");
            data.Columns.Add("NAME");
            foreach (KeyValuePair<string, string> pair in ConfigHelper.GetLoginTo())
            {
                data.Rows.Add(pair.Key, pair.Value);
            }
            this.cmbLoginTo.DataSource = data;
            this.cmbLoginTo.ValueMember = "ID";
            this.cmbLoginTo.DisplayMember = "NAME";
            if (data.Rows.Count > 0)
            {
                this.cmbLoginTo.EditValue = data.Rows[0]["ID"];
            }
        }

        private bool Login()
        {
            if (!BaseSystemInfo.Logined && this.cmbLoginTo.Enabled)
            {
                ConfigHelper.LoginTo = cmbLoginTo.EditValue.ToString();
                ConfigHelper.GetConfig(BaseConfiguration.Instance);
                if (BaseConfiguration.Instance.RunMode == RunMode.Remoting)
                {
                    this.cmbLoginTo.Enabled = false;
                    RemotingConfiguration.Configure(ConfigHelper.FielName, false);
                }
            }
            string statusCode = string.Empty;
            string statusMessage = string.Empty;
            BaseUserInfo userInfo = ServiceManager.Instance.LoginService.UserLogin(base.UserInfo, this.txtUsername.Text, this.txtPassword.Text, out statusCode, out statusMessage);
            if (statusCode == StatusCode.OK.ToString())
            {
                if ((userInfo != null) && (userInfo.ID.Length > 0))
                {
                    this.Login(userInfo);
                    if (BaseSystemInfo.SavePassword)
                    {
                        this.SaveLoginInfo();
                    }
                    if (base.Parent == null)
                    {
                        base.Hide();
                        if (!BaseSystemInfo.Logined)
                        {
                            Form form = CacheManager.Instance.GetForm(BaseSystemInfo.MainAssembly, BaseConfiguration.Instance.MainForm);
                            ((IBaseMainForm)form).InitService();
                            ((IBaseMainForm)form).InitForm();
                            form.Text = BaseSystemInfo.SoftFullName;
                            ClientCache.Instance.GetPermission(base.UserInfo);
                            form.ShowDialog();
                            base.Close();
                        }
                    }
                    BaseSystemInfo.Logined = true;
                    this.LoginCount = 0;
                    if (base.Owner != null)
                    {
                        ((IBaseMainForm)base.Owner).InitService();
                        ((IBaseMainForm)base.Owner).InitForm();
                        ((IBaseMainForm)base.Owner).CheckMenu();
                        return true;
                    }
                    if (base.Parent != null)
                    {
                        ((IBaseMainForm)base.Parent.Parent).InitService();
                        ((IBaseMainForm)base.Parent.Parent).InitForm();
                        ((IBaseMainForm)base.Parent.Parent).CheckMenu();
                        base.Close();
                    }
                }
                return true;
            }

            XtraMessageBox.Show(statusMessage, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            this.txtPassword.Focus();
            this.txtPassword.SelectAll();
            return false;
        }

        private void Login(BaseUserInfo userInfo)
        {
            BaseSystemInfo.Login(userInfo);
        }

        private void SaveLoginInfo()
        {
            this.Cursor = Cursors.WaitCursor;
            if (BaseSystemInfo.SavePassword)
            {
                try
                {
                    RegistryKey key = Registry.LocalMachine.CreateSubKey(@"Software\JGsoft\" + BaseConfiguration.Instance.SoftName);
                    key.SetValue("CurrentUsername", this.txtUsername.Text);
                    key.SetValue("CurrentPassword", this.txtPassword.Text);
                }
                catch (Exception exception)
                {
                    base.ProcessException(exception);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void SetControlState()
        {
            if (BaseSystemInfo.AllowNullPassword)
            {
                this.labPasswordReq.Visible = false;
            }
            if (BaseSystemInfo.Logined)
            {
                base.CancelButton = this.btnCancel;
                this.btnCancel.Show();
                this.btnExit.Hide();
            }
            else
            {
                base.CancelButton = this.btnExit;
                this.btnExit.Show();
                this.btnCancel.Hide();
            }
        }

        private void SetHelp()
        {
            base.HelpButton = true;
        }

        private void SetLoginTo(string loginTo)
        {
            if (!string.IsNullOrEmpty(loginTo))
            {
                this.cmbLoginTo.EditValue = loginTo;
            }
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar == '\r') && this.CheckInput())
            {
                this.Login();
            }
        }

        public class ListItem
        {
            private string id = string.Empty;
            private string name = string.Empty;

            public ListItem(string sid, string sname)
            {
                this.id = sid;
                this.name = sname;
            }

            public override string ToString()
            {
                return this.name;
            }

            public string ID
            {
                get
                {
                    return this.id;
                }
                set
                {
                    this.id = value;
                }
            }

            public string Name
            {
                get
                {
                    return this.name;
                }
                set
                {
                    this.name = value;
                }
            }
        }
    }
}